package ynu.edu.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.dto.LoginRequest;
import ynu.edu.dto.RegisterRequest;
import ynu.edu.dto.UserResponse;
import ynu.edu.entity.User;
import ynu.edu.exception.AuthenticationException;
import ynu.edu.exception.ResourceNotFoundException;
import ynu.edu.repository.UserRepository;
import ynu.edu.service.UserService;

import java.util.Optional;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 用户登录
     * @param request 登录请求
     * @return 登录用户信息
     */
    @Override
    public UserResponse login(LoginRequest request) {
        try {
            System.out.println("UserService.login 开始处理: userId=" + request.getUserId());
            
            // 参数校验
            if (request == null) {
                throw new AuthenticationException("登录请求不能为空");
            }
            
            if (request.getUserId() == null || request.getUserId().trim().isEmpty()) {
                throw new AuthenticationException("用户ID不能为空");
            }
            
            if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
                throw new AuthenticationException("密码不能为空");
            }
            
            // 尝试查询用户
            System.out.println("正在查询用户: " + request.getUserId());
            Optional<User> userOptional;
            try {
                userOptional = userRepository.findByUserId(request.getUserId());
                System.out.println("查询用户完成，结果: " + (userOptional.isPresent() ? "存在" : "不存在"));
            } catch (Exception e) {
                System.err.println("数据库查询异常: " + e.getClass().getName() + ": " + e.getMessage());
                e.printStackTrace();
                throw new AuthenticationException("数据库查询异常: " + e.getMessage());
            }
            
            // 验证用户是否存在
            if (!userOptional.isPresent()) {
                System.err.println("用户不存在: " + request.getUserId());
                throw new AuthenticationException("用户不存在");
            }
            
            User user = userOptional.get();
            System.out.println("找到用户: " + user.getUserName() + ", 正在验证密码");
            
            // 检查密码是否匹配
            if (!user.getPassword().equals(request.getPassword())) {
                System.err.println("密码不匹配: userId=" + request.getUserId());
                throw new AuthenticationException("密码错误");
            }
            
            // 检查用户是否被删除
            if (user.getDelTag() != null && user.getDelTag() == 0) {
                System.err.println("用户已被删除: userId=" + request.getUserId());
                throw new AuthenticationException("用户已被删除");
            }
            
            System.out.println("登录成功: userId=" + request.getUserId());
            return UserResponse.fromEntity(user);
        } catch (AuthenticationException ae) {
            // 直接抛出认证异常
            throw ae;
        } catch (Exception e) {
            System.err.println("登录处理未预期异常: " + e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
            throw new AuthenticationException("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 用户注册
     * @param request 注册请求
     * @return 注册用户信息
     */
    @Override
    @Transactional
    public UserResponse register(RegisterRequest request) {
        // 检查用户ID是否已存在
        Optional<User> existingUser = userRepository.findByUserId(request.getUserId());
        if (existingUser.isPresent()) {
            throw new AuthenticationException("用户ID已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUserId(request.getUserId());
        user.setUserName(request.getUserName());
        user.setPassword(request.getPassword());
        user.setUserSex(request.getUserSex());
        user.setUserImg("/default.jpg"); // 设置默认头像
        user.setDelTag(1); // 1: 正常
        
        // 保存用户
        user = userRepository.save(user);
        
        return UserResponse.fromEntity(user);
    }
    
    /**
     * 根据用户ID获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public UserResponse getUserById(String userId) {
        User user = userRepository.findByUserId(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户", "ID", userId));
        
        // 检查用户是否被删除
        if (user.getDelTag() != null && user.getDelTag() == 0) {
            throw new ResourceNotFoundException("用户已被删除");
        }
        
        return UserResponse.fromEntity(user);
    }
} 